<template>
  <div class="search-box">
    <el-autocomplete
      v-model="industryName"
      :fetch-suggestions="querySearchAsync"
      :debounce="400"
      placeholder="输入产业/行业名称查询"
      popper-class="auto-complete-search"
      value-key="industryName"
      clearable
      @select="handleSelect"
    >
      <template #prefix>
        <img class="search-icon" :src="searchIcon" alt="" />
      </template>
      <template #default="{ item }">
        <div
          class="option-item"
          v-html="formateText(item.industryName)"
          v-if="item.industryName"
        ></div>
      </template>
    </el-autocomplete>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { getIndustryByName } from '@/api/industryMap.js';
import searchIcon from '@/assets/images/industryMap/searchIcon.png';

const router = useRouter();

const industryName = ref('');
const automatedList = ref([]);
const querySearchAsync = async (keyWord, cb) => {
  if (!industryName.value) {
    automatedList.value = [{ industryName: '输入产业/行业名称查询' }];
    return cb(automatedList.value);
  }
  const res = await getIndustryByName({ industryName: keyWord });
  if (res.code == 200 && res.data && res.data.length) {
    automatedList.value = res.data;
    cb(automatedList.value);
  }
};
const formateText = (content) => {
  if (content && content != '') {
    let text = industryName.value;
    let regStr = `(${text})`;
    let reg = new RegExp(regStr, 'g');
    // 正则替换，关键词飘红
    return content.replace(
      reg,
      '<span style="color:#0b6eff;">' + text + '</span>'
    );
  }
};
//搜索框下拉点击舔砖详情
const handleSelect = (item) => {
  if (!item.id) {
    industryName.value = '';
    return;
  }
  const routeObj = {
    name: 'IndustryDetail',
    query: {
      code: item.id,
      industryType: item.industryType,
      name: encodeURIComponent(item.industryName),
    },
  };
  router.push(routeObj);
};
</script>
<style lang="scss" scoped>
.search-box {
  padding: 0 40px 14px 60px;
  .search-icon {
    width: 30px;
    margin-right: 10px;
  }
}
:deep(.el-input__wrapper) {
  padding: 0 20px;
  background: #ffffff;
  border-radius: 15px;
  box-shadow: none;
  line-height: normal;
}
:deep(.el-input__inner) {
  height: 56px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 22px;
  color: #aaaaaa;
  line-height: normal;
}
:deep(input::-webkit-input-placeholder) {
  font-size: 22px;
  color: #aaaaaa;
}
</style>
<style lang="scss">
.auto-complete-search {
  .el-popper__arrow {
    display: none;
  }
  .option-item {
    height: 60px;
    line-height: 60px;
    font-size: 22px;
  }
}
</style>
